package org.demo.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Command {

	public static void execute(final String cmd, final String path, final CommandCallback callback) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					System.out.println(cmd);
					final File file = new File(path);
					if (!file.exists()) {
						file.mkdir();
					}
					boolean result = true;
					Process process = Runtime.getRuntime().exec(cmd, null, file);
					InputStream inputStream = process.getInputStream();
					String line;
					BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
					while ((line = reader.readLine()) != null) {
						if (callback != null) {
							callback.updateLog(line);
						}
						if (line.contains("percent files transferred")) {
							try {
								String[] temps = line.split(" ");
								String temp = temps[temps.length - 1].split("%")[0];
								int value = (int) Double.parseDouble(temp);
								if (callback != null) {
									callback.updateProgress(value);
								}
							} catch (Exception e) {
								result = false;
								if (callback != null) {
									callback.failure(e.getMessage());
								}
							}
						}
						if (line.toLowerCase().contains("error") || line.toLowerCase().contains("fail")) {
							if (callback != null) {
								callback.failure(line);
							}
							result = false;
						}
						try {
							Thread.sleep(10);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					reader.close();
					inputStream.close();
					if (callback != null && result) {
						callback.success();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

}
